import { useEffect, useState } from "react"
import { useNavigate, useParams } from "react-router-dom"
import http from '../../api/index'
import { Button, Card, Flex, Input, Modal, Space } from 'antd';
import { Avatar, List } from 'antd';
import { UseFd } from "../../hooks/UseFd";
import '@wangeditor/editor/dist/css/style.css' // 引入 css


function Index() {
  const fd= UseFd()
  const { TextArea } = Input;
  const [list, setlist] = useState([])
  const [data,setData] = useState([])
  const [val, setVal] = useState('')
  const { id } = useParams()
  const getList = () => {
    http.get(`/api/article/${id}`).then(res => {
      setlist(res.data)
    })
  }
  useEffect(() => {
    getList()
  }, [])
  const token=localStorage.getItem('token')
  const nav=useNavigate()
  // ========================================================评论
  const fn = () => {
    if(!token){
      alert('请先登录')
      nav('/login')
    }else{
       http.post('/api/discuss', {
      userId: 47529555,// 47529555 用户id
      content: data,//评论内容
      //  commentId:number,//评论ID（非必填，回复评论时使用）
      articleId: id // 文章id 90
    }).then(res => {
      getList();
      setData('')
    })
    }
   
  }
  const onChange = e => {
    console.log('Change:', e.target.value);
  };
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false);
    http.post('/api/discuss', {
      userId: 47529555,// 47529555 用户id
      content: val,//评论内容
       commentId:isModalOpen.commentId,//评论ID（非必填，回复评论时使用）
      articleId: id // 文章id 90
    }).then(res => {
      console.log(res.data.rows);
      getList();
      alert('回复成功')
      setVal('')
    })
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  return (
    <div>
      <div style={{ textAlign: "center", border: '1px solid #ccc', margin: '20px' }}>
        <h1> 内容：{list.title}</h1>
        <h1> 内容：{list.content}</h1>
        <p>创建时间：{list.createdAt}</p>
        <p>更新时间{list.createdAt}</p>
      </div>

      <div style={{ border: '1px solid #ccc', margin: '50px' }}>
        <Flex vertical gap={32}>
          <TextArea
            showCount
            maxLength={100}
            value={data}
            placeholder="disable resize"
            onChange={(e)=>setData(e.target.value)}
            style={{ height: 120, resize: 'none' }}
          />
        </Flex>
        <Button style={{ float: 'right', marginTop: '15px' }}
          onClick={fn}
        >发送 </Button>
      </div>


      <div style={{ border: '1px solid #ccc', margin: '20px', padding: '20px' }}>
        <List
          itemLayout="horizontal"
          dataSource={list.comments}
          renderItem={(item, index) => (
            <div>
              <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
                <Card title={
                  <div>
                    <Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`} />
                    <span>{localStorage.getItem('name')}</span>
                  </div>
                } size="small">
                  {item.content}
                  <Button onClick={()=>setIsModalOpen({commentId:item.id})}>回复@jykl</Button>
                </Card>
                {
                  item.replies.map((item, index) => {
                    return <div style={{ marginLeft: '50px', borderLeft: '2px solid #ccc' }}>
                      <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
                        <Card title={
                          <div>
                            <Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`} />
                            <span>{localStorage.getItem('name')}</span>
                          </div>
                        } size="small">
                          {item.content}
                        </Card>
                      </Space>
                    </div>
                  })
                }
              </Space>
            </div>
          )}

        />
      </div>
      <Modal
        title="Basic Modal"
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Flex vertical gap={32}>
          <TextArea
            showCount
            maxLength={100}
            value={val}
            placeholder="disable resize"
            onChange={(e)=>setVal(e.target.value)}
            style={{ height: 120, resize: 'none' }}
          />
        </Flex>
      </Modal>
    </div>
  )
}

export default Index
